<template>
  <div class="swiper">
    <div class="swiper-wrapper">
      <div class="swiper-slide" v-for="(item,index) in imageList" :key="index" @click="clickSlide(index)">
        <img :src="item.imgUrl" :class="{active:currentIndex===index}">
      </div>
    </div>
      <div class="swiper-button-next"></div>
      <div class="swiper-button-prev"></div>
  </div>
</template>

<script>
import Swiper from 'swiper/bundle'

export default {
  name: "ImageList",
  data() {
    return {
      currentIndex: 0
    }
  },
  /* 接收父组件传递的props */
  props: {
    imageList: {
      type: Array,
      default: () => ([])
    }
  },
  methods: {
    /* 初始化swiper的回调函数 */
    renderSwiper() {
      const swiper = new Swiper('.swiper', {
        speed: 2000,
        loop:true,
        slidesPerView: 4,
        navigation: {
          nextEl: '.swiper-button-next',
          prevEl: '.swiper-button-prev',
        }
      })
    },
    /* 点击小图片的回调函数 */
    clickSlide(index) {
      this.currentIndex = index
      this.$eventBus.$emit("getIndex", this.currentIndex)
    }
  },
  watch: {
    imageList: {
      handler(newValue, oldValue) {
        this.$nextTick(() => {
          this.renderSwiper()
        })
      }
    }
  }
}
</script>

<style lang="less" scoped>
.swiper {
  position: relative;
  height: 56px;
  width: 412px;
  box-sizing: border-box;
  padding: 0 12px;

  .swiper-wrapper {
    /* 通过改变animation-timing-function 制作弹性切换效果 */
    transition: 2s cubic-bezier(0.68, -0.4, 0.27, 1.34) 0.2s;

    .swiper-slide {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 56px;
      height: 56px;
      cursor: pointer;

      img {
        border: 1px solid #ccc;
        padding: 2px;
        width: 50px;
        height: 50px;
        display: block;

        &.active {
          border: 1px solid #f60;
        }

      }
    }
  }

  .swiper-button-next {
    left: auto;
    right: 0;
  }

  .swiper-button-prev {
    left: 0;
    right: auto;
  }

  .swiper-button-next,
  .swiper-button-prev {
    box-sizing: border-box;
    width: 12px;
    height: 56px;
    background: rgb(235, 235, 235);
    border: 1px solid rgb(204, 204, 204);
    top: 0;
    margin-top: 0;

    &::after {
      font-size: 12px;
    }
  }

}
</style>
